import nodemailer from 'nodemailer';

// 邮件发送工具函数
const sendEmailAsync = (transporter, mailOptions) => {
  return new Promise((resolve, reject) => {
    transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
        console.error('邮件发送失败:', error);
        reject(error);
      } else {
        console.log('邮件发送成功:', info.response);
        resolve(info);
      }
    });
  });
};

// 创建邮件 transporter（从环境变量读取配置）
const createTransporter = () => {
  return nodemailer.createTransport({
    host: process.env.SMTP_HOST || "smtp.qq.com",
    port: parseInt(process.env.SMTP_PORT) || 465,
    secure: process.env.SMTP_SECURE === 'true' || true,
    auth: {
      user: process.env.SMTP_USER || "1690544550@qq.com",
      pass: process.env.SMTP_PASS || "znxogkkkexpbeeaj"
    },
    pool: true // 启用连接池
  });
};

// 发送验证码邮件
export const sendVerificationEmail = async (email, code) => {
  const transporter = createTransporter();
  
  const mailOptions = {
    from: process.env.SMTP_FROM || "1690544550@qq.com",
    to: email,
    subject: "邮箱验证码",
    text: `您的验证码是：${code}，5分钟内有效。`
  };
  
  return await sendEmailAsync(transporter, mailOptions);
};

// 发送登录通知邮件
export const sendLoginNotification = async (
  email,
  username,
  currentIp,
  currentDevice,
  currentTime,
  lastIp,
  lastDevice
) => {
  const transporter = createTransporter();
  
  const mailOptions = {
    from: process.env.SMTP_FROM,
    to: email,
    subject: "[安全提醒] 账户登录通知",
    html: `
      <div style="padding: 20px;">
        <p>您好，${username}：</p>
        <p>您的账户于 ${currentTime.toLocaleString()} 登录。</p>
        <p><strong>登录IP：</strong>${currentIp}</p>
        <p><strong>登录设备：</strong>${currentDevice}</p>
        
        
        <p>如非本人操作，请立即修改密码。</p>
      </div>
    `
  };
  
  return await sendEmailAsync(transporter, mailOptions);
};

// 发送密码重置验证码邮件
export const sendResetPasswordCode = async (email, username, code) => {
  const transporter = createTransporter();
  
  const mailOptions = {
    from: process.env.SMTP_FROM,
    to: email,
    subject: "[密码重置] 您的验证码",
    html: `
      <div style="font-family: Arial, sans-serif; padding: 20px;">
        <h3>密码重置请求</h3>
        <p>您好，${username}：</p>
        <p>您请求重置账户密码，验证码如下（10分钟内有效）：</p>
        <div style="font-size: 1.5rem; font-weight: bold; margin: 1rem 0; color: #3b82f6;">
          ${code}
        </div>
        <p>如果这不是您本人操作，请忽略此邮件。</p>
      </div>
    `
  };
  
  return await sendEmailAsync(transporter, mailOptions);
};